package com.spring.flowable.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.spring.flowable.convert.BpmnConvert;
import com.spring.flowable.domain.ProcessNode;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.validation.ProcessValidator;
import org.flowable.validation.ProcessValidatorFactory;
import org.flowable.validation.ValidationError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author liuzhiqiang
 */
@RestController
@CrossOrigin
@Slf4j
public class FlowableController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;

    @PostMapping("/create")
    public String test(@RequestBody ProcessNode processNode) {
        BpmnModel bpmnModel = BpmnConvert.toBpmn(processNode);

        //3、验证BpmnModel 是否合法
        ProcessValidatorFactory processValidatorFactory=new ProcessValidatorFactory();
        ProcessValidator defaultProcessValidator = processValidatorFactory.createDefaultProcessValidator();
        //验证失败信息的封装ValidationError
        List<ValidationError> validate = defaultProcessValidator.validate(bpmnModel);
        //validate 大于0说明有错误
        if (CollectionUtil.isNotEmpty(validate)) {
            for (ValidationError validationError : validate) {
                log.error(validationError.toString());
            }
        } else {
            repositoryService.createDeployment().addBpmnModel("",bpmnModel);
        }
        return "ok";
    }
}
